package com.note.app.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.note.common.domain.Tag;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 标签Mapper
 */
@Mapper
public interface TagMapper extends BaseMapper<Tag> {

    /**
     * 分页查询用户标签列表
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @return 分页结果
     */
    @Select("SELECT * FROM tag WHERE user_id = #{userId} AND deleted = 0 ORDER BY created_at DESC")
    IPage<Tag> selectPageByUserId(Page<Tag> page, @Param("userId") Long userId);
    
    /**
     * 查询笔记的所有标签
     * 
     * @param noteId 笔记ID
     * @return 标签列表
     */
    @Select("SELECT t.* FROM tag t " +
            "INNER JOIN note_tag nt ON t.id = nt.tag_id " +
            "WHERE nt.note_id = #{noteId} AND t.deleted = 0 AND nt.deleted = 0")
    List<Tag> selectTagsByNoteId(@Param("noteId") Long noteId);
    
    /**
     * 查询用户的所有标签
     * 
     * @param userId 用户ID
     * @return 标签列表
     */
    @Select("SELECT * FROM tag WHERE user_id = #{userId} AND deleted = 0 ORDER BY name")
    List<Tag> selectAllByUserId(@Param("userId") Long userId);
    
    /**
     * 根据名称查询用户标签
     * 
     * @param userId 用户ID
     * @param name 标签名称
     * @return 标签
     */
    @Select("SELECT * FROM tag WHERE user_id = #{userId} AND name = #{name} AND deleted = 0 LIMIT 1")
    Tag selectByUserIdAndName(@Param("userId") Long userId, @Param("name") String name);

    /**
     * 查询笔记的所有标签名称
     *
     * @param noteId 笔记ID
     * @return 标签名称列表
     */
    @Select("SELECT t.name FROM tag t JOIN note_tag nt ON t.id = nt.tag_id WHERE nt.note_id = #{noteId} AND t.deleted = 0")
    List<String> findTagNamesByNoteId(@Param("noteId") Long noteId);

    /**
     * 根据标签名称列表查询标签ID列表
     *
     * @param tagNames 标签名称列表
     * @return 标签ID列表
     */
    @Select({"<script>",
            "SELECT id FROM tag WHERE deleted = 0 AND name IN ",
            "<foreach collection='tagNames' item='name' open='(' separator=',' close=')'>",
            "#{name}",
            "</foreach>",
            "</script>"})
    List<Long> findTagIdsByNames(@Param("tagNames") List<String> tagNames);

    /**
     * 根据标签ID列表查询包含这些标签的笔记ID列表
     *
     * @param tagIds 标签ID列表
     * @return 笔记ID列表
     */
    @Select({"<script>",
            "SELECT DISTINCT note_id FROM note_tag WHERE tag_id IN ",
            "<foreach collection='tagIds' item='tagId' open='(' separator=',' close=')'>",
            "#{tagId}",
            "</foreach>",
            "</script>"})
    List<Long> findNoteIdsByTagIds(@Param("tagIds") List<Long> tagIds);
} 